/*本模块功能:院系管理(管理员)
        编写者:朱光曜
        编写时间:2017.11.03
        editor:yxj
        20180524
        */
$(function() {
	var string1 = '<tr>' +
		'<th class="col-lg-2"><input type="checkbox" name="controlAll" id="controlAll" class="allCheck"></th>' +
		'<th class="col-lg-9">院系名称</th>' +
		'<th class="col-lg-4">操作</th>' +
		'</tr>';
	/*列表头部*/
	var confirm1 = new  Confirm;
	var Alert1 = new  Alert;
	var Alert2 = new  Alert;

	

	

	function tabelModel(data) {
		/*列表内容*/	

		return '<tr data-num="0">' +
			'<td class="col-lg-2"><input value="0" name="selecteds" type="checkbox" class="oneCheck"  departmentId="'+data.departmentList[key].departmentId+'"/></td>' +
			'<td class="col-lg-10"  title="'+data.departmentList[key].departmentName+'">'+data.departmentList[key].departmentName+'</td>' +
			'<td class="col-lg-4">' +
			'<a href="javascript:;" class="set">修改</a>' +
			'<a class="initialization" href="javascript:;">专业管理</a>' +
			'</td>' +
			'</tr>';

	}
	var loading1 = new Loading();//监控全局ajax添加loading
	loading1.init();
    $(document).ajaxSend(function(){
		loading1.show();
		
		});
	$(document).ajaxStop(function(){
		loading1.hide();
		
		});
	document.addEventListener('DOMSubtreeModified',function(e){//去除空格
	$(".publicText").attr("maxlength","50");
	$.map($(".publicText"),function (opt) {//长度限制
		maxLengthLimit.init(opt);
	});
	$(".publicText").bind('input propertychange',function(){
		
	    var regy = /\s/g;
		if(regy.test($(this).val())){
			$(this).val($(this).val().replace(/\s|\xA0/g,"")) ;
		}
	    });
	});
	var nowData = 1;
	var index = {
		init: function() {
			this.bind();
		},
		bind: function() {
			var self = this;
			this.data_content = {}; //搜索集
			this.tab_content = {}; //列表集
			this.parameter = {
				"pageNow": 1,
				"pageSize": 10
			};
           
            	
           
			this.postData(this.parameter, nowData);//加载列表

			$(".deleteDepartment").off("click").on("click", function() {//点击全选
				self.delListEvent();
			});
			$(".addDepartment").off("click").click(function() {//添加院系
				var method='<div class=" inputRight" style="width:260px;margin: 0 auto;"><label for="departName">院系名称:&ensp;</label><input autocomplete="off" type="text" id="departmentName" class="publicText" placeholder="请输入院系名称" /></div>';
				var $self=self;
				var sub = function() {
					var departmentName =$("#departmentName" ).val();
					if(departmentName == "") {
					
						$self.alert1("请输入院系名称","fail");
						return;
					} else if(verification.specialCode(departmentName) !== true) {
						self.alert1("不能输入特殊字符(@/'\"#$%&^*)","fail");
						return;
					}
					var parameter = {
						"departmentName": departmentName
				
					};
					
					$.ajax({
						type: "post",
						url: "addDepartment",
						async: true,
						data: {
							"jsonStr": JSON.stringify(parameter)
						},
				
						success: function(msg) {
				
							var msgNew = JSON.parse(msg);
							var self = $self;
							if(msgNew.result == "success") {
								self.alerty("添加成功");
				
							} else {
								if(msgNew.failMsg){
									self.alert1(msgNew.failMsg);
								}else{
									self.alert1("添加失败");
								}
								
							}
				
						},
						error: function(data, status, xhr) {
							var json = JSON.stringify({
								"pageName": "error"
						    });
							window.location.href = "skipPage?jsonStr=" + json;

						}
					});
				};
				
				self.addUser("添加院系", method, sub);//添加院系

			});

		},
		addUser: function(message1, method1, after) { //编辑和增加院系
			Alert1.contenthead = message1;
			Alert1.content = method1;
			Alert1.success = after;

			Alert1.init();
		
			$(".sex input" ).off("click").click(function() {

				$(this).next("label").addClass("checked").siblings("label").removeClass("checked");
			});

			$(".hover-btn" ).html("保存");
			$(".alert_img" ).hover(function() {
				Alert1.success = function() {};
			}, function() {
				Alert1.success = after;
			});
			Alert1.show();

		},
		postData: function(par_data, nowData,hunt) { //获得搜索及列表数据
			var self = this;
			var parameter = par_data;

			$.ajax({
				type: "post",
				url: "skipDepartMentMana",
				async: true,
				data: {
					"jsonStr": JSON.stringify(parameter)
				},
				success: function(data, status, xhr) {
					var new_data = JSON.parse(data);
					if(new_data.result == "success"){
                        if(hunt) {
                            self.tab_content = new_data;

                            self.tab_add();
                        } else {

                            self.data_content = new_data;
                            self.tab_content = new_data;

                            self.add();
                            self.tab_add();
                        }

                        var sumpage = new_data.totalPage;
                        if(sumpage<1){sumpage=1;};
                        var nowpage = new_data.pageNow;
                        var pagenumber = 10;
                        var parame = parameter;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {

                                nowpage = p;

                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                if(!parameter) {
                                    parameter = {
                                        "pageNow": nowpage,
                                        "pageSize": 10
                                    };

                                } else {
                                    parameter.pageNow = nowpage;

                                }
                                $.ajax({
                                    type: "post",
                                    url: "skipDepartMentMana",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(parameter)
                                    },
                                    async: true,
                                    success: function(msg) {
                                        //获取院系
                                        var msgNew = JSON.parse(msg);
                                        self.tab_content = msgNew;

                                        self.tab_add();
                                    },
                                    error: function(data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                            }
                        });
					}else{
						if(new_data.failMsg == "暂无权限"){
                            parent.location.reload(true);
						}
					}

				},
				error: function(data, status, xhr) {
					var json = JSON.stringify({
						"pageName": "error"
				    });
					window.location.href = "skipPage?jsonStr=" + json;

				}
			});
		},
		add: function() { //搜索追加
			var self = this;
			var data = self.data_content;
			for(key in data.depAllList) {
				$("#departNames").append("<option depId=" + data.depAllList[key].depId + ">" + data.depAllList[key].depName + "</option>");
			}

			$(".funBox .searchBtn").off("click").click(function() { //搜索点击

				
				var departmentName = $("#keyWord").val();
				var nowData = 1;
				if(verification.specialCode(departmentName) !== true) {
					self.alert1("不能输入特殊字符(@/'\"#$%&^*)");
				}
				var parameter = {
					"departmentName": departmentName,
				

					"pageNow": 1,
					"pageSize": 10
				};
				//遍历删除空元素
				var j=0;
				for(i in parameter){
					if(j==0){j++;continue;}
					if(parameter[i]==null||parameter[i]==""){
						delete parameter[i];
					}
					if(!isNaN(parameter[i])){
						parameter[i]=Number(parameter[i]);
					}
				}

              
				self.postData(parameter, nowData,1);
			});

		},
		tab_add: function() { //列表追加

			var self = this;
			var data = self.tab_content;
			var table = string1;

			//data.selectList={};

			var i = 0;
			for(key in data.departmentList) {
				i++;
			}

			if(i > 0) {

				for(key in data.departmentList) {

					table += tabelModel(data);
				}

				$(".mainContent .tableBox").html(table);
			} else {
				var trImg = "<tr><td colspan='3'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td/tr>";
				$(".mainContent .tableBox").html(string1 + trImg);
			}
			
			//设置列表宽度(最大为9)
			var numMax = 0;
			$(".tableBox tr th").each(function() {
				var str = $(this).attr("class");
				var num = str.lastIndexOf("col-lg-") + 7;
				var num1 = parseFloat(str.substring(num, num + 1));
				numMax += num1;
			});
			
			$(".tableBox tr th").each(function() {
				var str = $(this).attr("class");
				var num = str.lastIndexOf("col-lg-") + 7;
				var num1 = parseFloat(str.substring(num, num + 1));
				
				$(this).css("width",num1 / numMax * 100+ "%");
			});
			self.allCheckEvent();
			$(".set").off("click").click(function() { //修改信息
				var method = '<div class=" inputRight" style="width:260px;margin: 0 auto;"><label for="departName">院系名称:&ensp;</label><input  type="text" id="departmentName" class="publicText" value="'+$(this).parents("tr").children("td").eq(1).html()+'" /></div>';
				var $self = self;
				var departmentId=$(this).parents("tr").children("td").eq(0).children(".oneCheck").attr("departmentId");
				
				var sub = function() {
					var departmentName = $("#departmentName" ).val();
					//验证
					
					if(departmentName == "") {
					
						$self.alert1("请输入院系名称","fail");
						return;
					} else if(verification.specialCode(departmentName) !== true) {
						self.alert1("不能输入特殊字符(@/'\"#$%&^*)","fail");
						return;
					}
				
					var parameter = {
						"departmentName": departmentName,
						"departmentId":departmentId
				       
					};
					
					
					$.ajax({
						type: "post",
						url: "saveDepartment",
						async: true,
						data: {
							"jsonStr": JSON.stringify(parameter)
						},
				
						success: function(msg) {
				
							var msgNew = JSON.parse(msg);
							var self = $self;
							if(msgNew.result == "success") {
								self.alerty("提交成功");
				
							} else {
								if(msgNew.failMsg){
									self.alert1(msgNew.failMsg);
								}else{
									self.alert1("提交失败");
								}
							}
				
						},
						error: function(data, status, xhr) {
							var json = JSON.stringify({
								"pageName": "error"
						    });
							window.location.href = "skipPage?jsonStr=" + json;

						}
					});
				};
				
				self.addUser("修改院系", method, sub);
			});
            
			$(".initialization").off("click").click(function() { //专业管理
				var json=JSON.stringify({
					"pageName":"adminOrganizationalProfessional",
					"paramData":{
						"departmentId":Number($(this).parents("tr").children("td").eq(0).children(".oneCheck").attr("departmentId"))
					}
				});
				
				window.location.href="skipPage?jsonStr="+json;
				//$("#ifMain,parent.document").attr("src","skipPage?jsonStr=" + json);
			});
		},
		alert1: function(content1,state) { //confirm提示

			Alert2.contenthead = "提示";
			Alert2.content = content1;

			Alert2.success = function() {
                $(".alert").eq(0).show();
                $(".abs_bg").eq(1).show();
                $(".alert").eq(1).remove();

			};
			

			Alert2.init();
			Alert2.show();
			$(".alert_content").css("height","auto");
		},
        alerty: function(content1,state) { //confirm提示

            Alert2.contenthead = "提示";
            Alert2.content = content1;

            Alert2.success = function() {
                window.location.reload(true);
            };


            Alert2.init();
            Alert2.show();
            $(".alert_content").css("height","auto");
        },
		allCheckEvent: function() {
			//全选
			allCheck.init("controlAll", "oneCheck");
		},
		delListEvent: function() { //批量删除
			var $_self = this;
			if($(".oneCheck[value=1]").length == 0) {
                Alert1.contenthead = "提示信息";
				Alert1.content = "请选择要删除的院系";
				Alert1.success = function() {};
				Alert1.init();
				Alert1.show();
			} else {

				confirm1.success = function() {
					var list = [];
					$(".box_1 tr td .oneCheck").each(function() {
						if(parseInt($(this).val()) == 1) {
							list.push($(this).attr("departmentId"));

						}

					});
					
					var deleteDepartmentparameters =list;
					var self = $_self;
					$.ajax({
						type: "post",
						url: "delDepartment",
						async: true,
						data: {
							"jsonStr": JSON.stringify(deleteDepartmentparameters)
						},

						success: function(msg) {

							var msgNew = JSON.parse(msg);

							if(msgNew.result == "success") {
								self.alerty("删除成功");
							} else {
								//self.alert1(msgNew.failMsg);
								if(msgNew.failMsg){
									self.alerty(msgNew.failMsg);
								}else{
									self.alerty("删除失败");
								}

							}

						},
						error: function(data, status, xhr) {
							var json = JSON.stringify({
								"pageName": "error"
						    });
							window.location.href = "skipPage?jsonStr=" + json;

						}
					});
				};
				var num = 0;
				$(".box_1 tr td .oneCheck").each(function() {
					if(parseInt($(this).val()) == 1) {
						num++;
					}

				});
				if(num < 2) {
					confirm1.content = "确定删除这个院系吗";
				} else {
					confirm1.content = "确定删除这<a href='javascript:void(0)'>" + num + "</a>个院系吗";
				}

				confirm1.init();
				$(".alert_content a" ).css({
					"margin": "2px",
					"color": "#c82011",
					"text-decoration": "underline"
				});
				confirm1.show();

			}
		}

	};
	index.init();

});